/**
    @author: ASUS
    @date: 2021/2/20
    @Describe:
**/
package db

import (
	"fmt"
	_ "github.com/influxdata/influxdb1-client"
	client "github.com/influxdata/influxdb1-client/v2"
	"log"
	"sync"
	"time"
)

var (
	once sync.Once
	cli  client.Client
	err  error
)

func InitClient(hostIp, userName, password string, timeout int) client.Client {
	once.Do(func() {
		cli, err = client.NewHTTPClient(client.HTTPConfig{
			Addr:     hostIp,
			Username: userName,
			Password: password,
			Timeout:  time.Duration(timeout) * time.Second,
		})
		if err != nil {
			panic(fmt.Sprintf("influxdb client connect fali  %s", err.Error()))

		}
	})

	return cli

}

// query
/**
cli
cmd 查询语句
database  库名
*/
func QueryDB(cli client.Client, cmd string, database string) (res []client.Result, err error) {
	q := client.Query{
		Command:  cmd,
		Database: database,
	}
	if response, err := cli.Query(q); err == nil {
		if response.Error() != nil {
			return res, response.Error()
		}
		res = response.Results
	} else {
		return res, err
	}
	return res, nil
}

// insert
func WritesPoints(cli client.Client, database, pointName string, tags map[string]string, fields map[string]interface{}, t time.Time) {

	bp, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database:  database,
		Precision: "s", //精度，默认ns
	})
	fmt.Println(11)
	if err != nil {
		panic(fmt.Sprintf("influxdb client.NewBatchPoints fali %s", err.Error()))
	}

	pt, err := client.NewPoint(pointName, tags, fields, t)
	if err != nil {
		panic(fmt.Sprintf("influxdb client.NewPoint fali %s", err.Error()))
	}

	bp.AddPoint(pt)
	err = cli.Write(bp)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("insert success")
}
